package com.hc.util;

import com.hc.dao.IUUserDAO;
import com.hc.entity.UUser;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

public class JWTAuthorizingRealm extends AuthorizingRealm {

    IUUserDAO userDAO;


    @Autowired
    public void setUserDAO(IUUserDAO userDAO) {
        this.userDAO = userDAO;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userName = (String) authenticationToken.getPrincipal();
        String passWord = new String((char[]) authenticationToken.getCredentials());
        List<UUser> userArr = userDAO.getByName(userName);
        if (userArr == null) {
            throw new AuthenticationException();
        }

        UUser userEnt = userArr.get(0);
        if (userEnt == null || !passWord.equals(userEnt.getPassword())) {
            throw new AuthenticationException();
        }
        return new SimpleAuthenticationInfo(userName, passWord, getName());
    }
}
